package com.afeng.executor.demo;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Description : 任务管理器
 * @author      : yfbian
 */
public class ThreadPoolExecutorManager {
    
    //@Autowired
    //private static ExecutorCommonConfiguration executorCommonConfiguration;
	
	private static ThreadPoolExecutor executorService = null;

	public static AtomicInteger sendWorkerSize = new AtomicInteger();

	private static Integer queueSize = 1000;

	static {
		init();
	}

	public static void init() {
		
		// 初始化线程数
//		int threadCoreSize = executorCommonConfiguration.getCorePoolSize();
//		int threadMaxSize = executorCommonConfiguration.getMaximumPoolSize();
//		long keepLive = executorCommonConfiguration.getKeepAliveTime();
//		queueSize = executorCommonConfiguration.getQueueSize();
	    
	    int threadCoreSize = 3;
	    int threadMaxSize = 10;
	    long keepLive = 1;
	    queueSize = 20;
		
		executorService = new ThreadPoolExecutor(threadCoreSize, threadMaxSize,keepLive, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>(queueSize));
		
	}

	public static boolean addTask(JobTaskVo jobTaskVo,CountDownLatch latch) {
		if (executorService == null){
			init();
		}
		
		System.out.println("executorService.getActiveCount():" + executorService.getActiveCount());
		System.out.println("executorService.getCorePoolSize():" + executorService.getCorePoolSize());
		System.out.println("executorService.getQueue().size():" + executorService.getQueue().size());
		System.out.println("executorService.getPoolSize():" + executorService.getPoolSize());
			
		if (!isFull()) {
			sendWorkerSize.incrementAndGet();
			executorService.execute(new JobWorkerThread(jobTaskVo,latch));
			return true;
		} else{
		    sendWorkerSize.incrementAndGet();
            executorService.execute(new JobWorkerThread(jobTaskVo,latch));
			return false;
		}
		
	}

	private static boolean isFull() {
		//logger.info("当前活动的线程数:"+((ThreadPoolExecutor)executorService).getActiveCount());
		return sendWorkerSize.intValue() >= queueSize;
	}
	
	public static void close() {
	    executorService.shutdown();
	}
}
